<?php

 /****如果有颜色，则获取颜色列表到产品里**/
function get_goods_color_list($spec_array,$string_type='颜色'){
	        $color_array = array();
	        $spec_array = stripslashes($spec_array);//去掉引号前面的斜杠
			  $arr_par = json_decode($spec_array,true);
			  foreach($arr_par as $k =>$v){
			    $val[] = $v['val'];
				$name[] = $v['name'];
			   }
			  // print_r($name); 
			   $exists_key = array_search($string_type,$name);
			    if($exists_key>-1){
				 $color_str = $val[$exists_key];
				 $color_array = explode('|',$color_str);
				}
			  unset($val);
			  unset($name);
			  return $color_array;
	
}

/**
 * 对字符进行强加密
 * @param string $str 待加密字符串
 */
function strongmd5($str) {
    return md5(md5($str) . 'river');
}


//获取当前URL
function curPageURL() 
{
  $pageURL = 'http';
 
  if ($_SERVER["HTTPS"] == "on") 
  {
    $pageURL .= "s";
  }
  $pageURL .= "://";
 
  if ($_SERVER["SERVER_PORT"] != "80") 
  {
    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  } 
  else
  {
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
  }
  
  return $pageURL;
}





/*****本地文件或网上地址******/
 function file_url_http($string){
	 if(!strstr($string,"http")){
	  return __ROOT__.$string;
	 }else{
	  return $string;
	 }
 }
 
 
/*****当前类别*******/
function get_menu_current($m,$a,$n=1){
if($m==$a){
  if($n==1){
	  return ' on';
  }else{
 return ' class="on"';
  }
}else{
	return '';
}
}

function priceTofixed($n){
return sprintf("%.2f", $n);
}

/******支付方式******/
 function get_payment_type($n=''){
	 $array = array(1=>'支付宝','2'=>'微信');
	 if($n>0){
	 return $array[$n];
	 }else{
	 return $array;
	 }
 }
 
 
/******退款状态******/
 function tuihuan_status($n){
 $array = array(0=>'已取消',1=>'退款处理中',2=>'退款成功',3=>'审核通过',4=>'审核不通过');
 return $array[$n];
}


 function tuihuan_status_array(){
 $array = array(0=>'已取消',1=>'退款处理中',2=>'退款成功',3=>'审核通过',4=>'审核不通过');
 return $array;
}


//退换货状态
function get_th_status($n){
 $array = array(0=>'已取消',1=>'退款处理中',2=>'退款成功',3=>'审核通过',4=>'审核不通过');
	return $array[$n];
}

 
 

/**
 * 显示时间
 * @param type $string
 * @param type $n
 * @return string
 */
function stringtime($string, $n = 1) {
    if ($string == '') {
        return '';
    } elseif ($n == 1) {
        return date("Y-m-d H:i:s", $string);
    }elseif($n==2){
		return date("Y-m-d", $string);
		}elseif($n==3){
			return date("Y-m-d H:i", $string);
			}elseif($n==4){
				return date("Y年m月d日 H:i:s", $string);
				} else {
        return date("Y/m/d", $string);
    }
}



/**
 * 显示时间
 * @param type $string
 * @param type $n
 * @return string
 */
function stringtoday($string, $n = 1) {
    if ($string == '') {
        return '';
    } elseif ($n == 1) {
		
        return date("Y-m-d H:i:s",strtotime($string));
    }elseif($n==2){
		return date("Y-m-d", strtotime($string));
		}elseif($n==3){
			return date("Y-m-d H:i", strtotime($string));
			}elseif($n==4){
				return date("Y年m月d日 H:i:s", strtotime($string));
				} else {
        return date("Y/m/d", strtotime($string));
    }
}


/*****文本输出***/

function trim_textarea($string)
{
	$string = nl2br(str_replace(' ',' &nbsp;',$string));
	return $string;
}



/**
 * 保留几位小数
 * @param float $data 基恩
 * @param int $num 小数位数
 */
function tofixed($data,$num) {
   return sprintf("%.".$num."f", $data);
}

 /*********字符串分隔成数组***********/
 function stringToarray($s,$do=','){
	 if($s==''){
	 $array = array();
	 return $array;
	 }
	 $array = explode($do,$s);
	 foreach($array as $k =>$v){
	 if($v==''){
	  unset($array[$k]);
	  }
	 }
	 return $array;
 
 }

/**
 * 删除文件
 * @param string $file 文件路径+文件名
 */
function delfile($file) {
    $file = $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . $file;
    if (file_exists($file)) {
        $result = unlink($file);
        return $result;
    } else {
        return false;
    }
}

/**
 * 删除文件夹内所有子文件夹和文件 
 */
function rmdirr($dirname) {
    if (!file_exists($dirname)) {
        return false;
    }
    if (is_file($dirname) || is_link($dirname)) {
        return unlink($dirname);
    }
    $dir = dir($dirname);
    if ($dir) {
        while (false !== $entry = $dir->read()) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            //递归
            rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
        }
    }
    $dir->close();
    return rmdir($dirname);
}

/*
 * 获取IP地址
 */

function getIP() {
    if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if (@$_SERVER["HTTP_CLIENT_IP"])
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    else if (@$_SERVER["REMOTE_ADDR"])
        $ip = $_SERVER["REMOTE_ADDR"];
    else if (@getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (@getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (@getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else
        $ip = "Unknown";
    return $ip;
}

/**
 * 生成随机文件名函数
 */
function randomname($length,$chars = '') {
    $hash = '';
    if($chars == '')
        $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    mt_srand((double) microtime() * 1000000);
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return date('YmdHis', time()) . $hash;
}

/**
 * 生成随机文件名函数
 */
function random($length,$chars = '') {
    $hash = '';
    if($chars == '')
        $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    mt_srand((double) microtime() * 1000000);
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

/**
 * 生成随机验证码
 */
function random_code($length) {
    $hash = '';
    $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    mt_srand((double) microtime() * 1000000);
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

/**
 * 计算UTF8字符占用空间的长度用于准确截取字符串
 * @param string $str 要截取的字符串
 * @return int 个数
 */
function utf8_strlen($str) {
    $ch_amont = 0;
    $en_amont = 0;
    $str = preg_replace("/(　| ){1,}/", " ", $str);
    for ($i = 0; $i < strlen($str); $i++) {
        $ord = ord($str{$i});
        if ($ord > 128)
            $ch_amont++;
        else
            $en_amont++;
    }
    return round($ch_amont / 3 * 2) + $en_amont * 2;
}

/**
 * 截取长字符
 */
function cut($string, $length, $dot = '...') {
    $string = strip_tags($string);
    $string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>'), $string);
    $strlen = utf8_strlen($string);
    if ($strlen <= $length)
        return $string;
    $strcut = '';
    $n = $tn = $noc = 0;
    while ($n < $strlen) {
        $t = ord($string[$n]);
        if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1;
            $n++;
            $noc++;
        } elseif (194 <= $t && $t <= 223) {
            $tn = 2;
            $n += 2;
            $noc += 2;
        } elseif (224 <= $t && $t < 239) {
            $tn = 3;
            $n += 3;
            $noc += 2;
        } elseif (240 <= $t && $t <= 247) {
            $tn = 4;
            $n += 4;
            $noc += 2;
        } elseif (248 <= $t && $t <= 251) {
            $tn = 5;
            $n += 5;
            $noc += 2;
        } elseif ($t == 252 || $t == 253) {
            $tn = 6;
            $n += 6;
            $noc += 2;
        } else {
            $n++;
        }
        if ($noc >= $length)
            break;
    }
    if ($noc > $length)
        $n -= $tn;
    $strcut = substr($string, 0, $n);
    $strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
    return $strcut . $dot;
}

/**
 * 替换图片为小图
 * @param string $str 待替换疃
 */
function replace_thumb($str, $path, $thumbpath) {
    return str_replace($path, $thumbpath, $str);
}

/**
 * 多图
 * @param type $arr
 * @param type $id
 * @return type
 */
function muti_pic_url($arr,$id=0){
    if($arr){
    $arr=array_filter(explode(",",$arr));
       if($id==1){
       return $arr[0];
       }else{
       return $arr;
        }
    }else{
     $arr = array();
     return $arr;
    }
   
}

//整型过滤函数 
function get_int($number) 
{ 
    return intval($number); 
} 

/**
 * 字符串省略号输出
 * @param <type> $string 字符串
 * @param <type> $max 开始替换位置
 * @param <type> $len 替换长度
 * @param <type> $rep 替换字符
 * @return <type>
 */
function shenglue($string, $max = 6, $len = 6, $rep = '*') {
    $strlen = strlen($string);
    if ($strlen <= $max)
        return $string;
    for ($i = 0; $i < $len; $i++) {
        $rstring .= $rep;
    }
    $left = $strlen - $max - strlen($rstring);
    return substr_replace($string, $rstring, $max, -$left);
}

/**
 * 中文字符串省略号输出
 * @param <type> $string 字符串
 * @param <type> $starNme 开始替换位置
 * @return <type>
 */
function hidename($string) {
    return substr($string, 0, 3) . '***' . substr($string, 9);
}

/**
 * 敏感词判断
 * @param string $content 内容
 * @param string $reg  敏感词，用/分割
 * @param int $a 大于0则内容存在敏感词
 */
function check_mingganci($content, $reg) {
    $array = preg_split('/[\/]+/', $reg);
    $a = 0;
    foreach ($array as $key => $val) {
        if ($val != '') {  //为空则不需要判断
            if (strpos($content, $val) > -1) {
                $a++;
            }
        }
    }
    return $a;
}



/**
 * 详细时间转换
 * @param type $time
 * @return type
 */
function tranTime($time) {
    $rtime = date("m-d H:i", $time);
    $htime = date("H:i", $time);
    $time = time() - $time;
    if ($time < 60) {
        $str = '刚刚';
    } elseif ($time < 60 * 60) {
        $min = floor($time / 60);
        $str = $min . '分钟前';
    } elseif ($time < 60 * 60 * 24) {
        $h = floor($time / (60 * 60));
        $str = $h . '小时前 ' . $htime;
    } elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time / (60 * 60 * 24));
        if ($d == 1)
            $str = '昨天 ' . $rtime;
        else
            $str = '前天 ' . $rtime;
    }
    else {
        $str = $rtime;
    }
    return $str;
}

//时间友好输出
function shijian() {
    $strTimeToString = "000001111223344444455566";
    $strWenhou = array('凌晨了，', '早上好！', '上午好！', '中午了，', '下午好！', '晚上好！', '夜深了，');
    echo $strWenhou[(int) $strTimeToString[(int) date('G', time())]];
}

//问候语输出
function wenhou() {
    $strTimeToString = "000001111223344444455566";
    $strWenhouExt = array('身体是革命的本钱，注意休息哦~',
        '朝自己微笑，准备开始精彩一天吧！',
        '好的习惯能让你终生受益哦',
        '休息一下，来顿美美的午餐吧~',
        '来杯热茶，让精神抖擞起来！',
        '来杯热茶，放松一下吧',
        '活跃了一天，还不洗洗睡么?',
    );
    echo $strWenhouExt[(int) $strTimeToString[(int) date('G', time())]];
}

/**
 *  加密函数
 * @param type $data 需加密的数据
 * @param type $key 密钥
 * @return type
 */
function encrypt($data, $key = 'river') {
    $prep_code = serialize($data);
    $block = mcrypt_get_block_size('des', 'ecb');
    if (($pad = $block - (strlen($prep_code) % $block)) < $block) {
        $prep_code .= str_repeat(chr($pad), $pad);
    }
    $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB);
    return base64_encode($encrypt);
}

/**
 * 解密函数
 * @param type $str 加密以后的字符串
 * @param type $key 密钥
 * @return type
 */
function decrypt($str, $key = 'river') {
    $str = base64_decode($str);
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = ord($str[($len = strlen($str)) - 1]);
    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) {
        $str = substr($str, 0, strlen($str) - $pad);
    }
    return unserialize($str);
}

function getAllNumber() {
    return array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
}

/**
 * 导出excel文件
 * @param type $expTitle
 * @param type $expCellName
 * @param type $expTableData
 */
  function exportExcel2($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("PHPExcel.PHPExcel");
       
        $objPHPExcel = new PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
        // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }  
        
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
        $objWriter->save('php://output'); 
        exit;   
    }

/**
 * 导出成Excel文件
 * @param type $filename 文件名
 * @param type $data_title 头部字段
 * @param type $data_content 内容
 * @param type $Sheet1
 * @param type $save_to_file 是否保存成文件,true保存
 * @param type $save_path 文件保存路径
 */
function excelExport($filename, $data_title, $data_content, $Sheet1 = "Sheet1", $save_to_file = false, $save_path = './Public/upload/xls/') {
    Vendor('PHPExcel.PHPExcel');
    //PHPExcel支持读模版 所以我还是比较喜欢先做好一个Excel的模版  比较好，不然要写很多代码  模版我放在根目录了
    //创建一个对象
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("fwshop");
    //获取当前活动的表
    $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet->setTitle($Sheet1); //工作表标签
    foreach ($data_title as $data_title_key => $data_title_value) {//写入文件表头内容
        $objActSheet->setCellValue($data_title_key, $data_title_value);
    }
    //现在就开始填充数据了  （从数据库中）  $data_content
    foreach ($data_content as $data_content_key => $data_content_value) {//写入 文件内容
        $objActSheet->setCellValue($data_content_key, $data_content_value);
    }
    //导出
    header('Content-Type: application/vnd.ms-excel;charset=utf-8');
    header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    if ($save_to_file) {
        $objWriter->save($save_path . $filename);
    } else {
        $objWriter->save('php://output');
        exit;
    }
}

/*
 * 验证手机
 */
function is_phone($phone) {
    return preg_match('/^0?1[3|4|5|8|7][0-9]\d{8}$/', $phone);
}

/*
 * 验证邮箱
 */
function is_email($email) {
    return preg_match('/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i', $email);
}

/*
 * 验证用户名
 */
function is_username($nickname) {
    return strlen($nickname) > 2;
    // return preg_match('/^[a-zA-Z0-9]{4,10}|[\x4e00-\u9fa5]{2,5}$/',$nickname);
}

/**
 * 读取Excel文件
 */
function excelImport($filename, $begin) {
    Vendor('PHPExcel.PHPExcel');
    //建立reader对象
    $PHPReader = new PHPExcel_Reader_Excel2007();
    if (!$PHPReader->canRead($filename)) {
        $PHPReader = new PHPExcel_Reader_Excel5();
        if (!$PHPReader->canRead($filename)) {
            return array();
        }
    }

    //建立excel对象，此时你即可以通过excel对象读取文件，也可以通过它写入文件
    $PHPExcel = $PHPReader->load($filename);
    /* 读取excel文件中的第一个工作表 */
    $currentSheet = $PHPExcel->getSheet(0);
    /* 取得最大的列号 */
    $allColumn = $currentSheet->getHighestColumn();
    /* 取得一共有多少行 */
    $allRow = $currentSheet->getHighestRow();

    $returnCell = '';
    //循环读取每个单元格的内容。注意行从1开始，列从A开始
    for ($rowIndex = $begin; $rowIndex <= $allRow; $rowIndex++) {
        for ($colIndex = 'A'; $colIndex <= $allColumn; $colIndex++) {
            $addr = $colIndex . $rowIndex;
            $cell = $currentSheet->getCell($addr)->getValue();
            if ($cell instanceof PHPExcel_RichText) {
                //富文本转换字符串
                $returnCell[$rowIndex][$colIndex] = $cell->__toString();
            } else {
                $returnCell[$rowIndex][$colIndex] = $cell;
            }
        }
    }
    return $returnCell;
}



/**
 * 文件大小格式化
 *@param type $filename 文件路径
 */
function getFilesize($filename) {
    $filename = $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . $filename;
    $size=filesize($filename);
    $mod = 1024; 
    $units = explode(' ','B KB MB GB TB PB');
    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }
    return round($size, 2) . ' ' . $units[$i];
}

/**
 * 发送邮箱
 * @param string $to 收件人
 * @param string $title 邮件标题
 * @param string $content 邮件内容
 * @param bool $is_html 是否HTML 默认是
 * @param string $charset 邮件编码 默认utf-8
 * @return bool ture发送成功 否则失败
 */
function sendMail($to, $title, $content, $is_html = true, $charset = 'utf-8') {
    Vendor('PHPMailer.PHPMailerAutoload');
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->SMTPAuth = true; //启用smtp认证
    $ModelEmail = new \Fwadmin\Model\ConfigEmailModel();
    $send = $ModelEmail->getSendEmailRand();
    $mail->Host = $send['smtp']; //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->Username = $send['username']; //你的邮箱名
    $mail->Password = decrypt($send['password']); //邮箱密码
    $mail->From =  $send['email']; //发件人地址（也就是你的邮箱地址）
    $mail->FromName = ''; //发件人姓名
    $mail->AddAddress($to, "尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML($is_html); // 是否HTML格式邮件
    $mail->CharSet = $charset; //设置邮件编码
    $mail->Subject = $title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = ""; //邮件正文不支持HTML的备用显示
    return($mail->Send());
}

/**
 * 短信发送函数
 * @param stirng $phone 手机号码
 * @param string $content 短信内容
 */
function sendSMS($phone,$content) {
    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
    $ConfigObj = new \Fwadmin\Model\ConfigModel();
    $smsapi = $ConfigObj->get("sms_url"); //短信网关
    $user = $ConfigObj->get("sms_username");; //短信平台帐号
    $pass = md5($ConfigObj->get("sms_password")); //短信平台密码
    $sms_name = $ConfigObj->get("sms_name"); //短信内容抬头
    $content = "【".$sms_name."】".$content;//要发送的短信内容
    $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
    $result =file_get_contents($sendurl) ;

    var_dump($result);die;
    if($result == "0") {
        return 'success';
    } else {
        return $statusStr[$result];
    }
}

 /**
 * 获取会员名称
 * @param int member_id 供应商ID
 * @return type 返回供应商名称
 */
function show_member_name($member_id) {
    $MemberObj = new \Fwadmin\Model\MemberModel();
    return $MemberObj->show_name($member_id);
}

 /**
 * 获取会员名称
 * @param int member_id 供应商ID
 * @return type 返回供应商名称
 */
function show_member_headpic($member_id) {
    $MemberObj = new \Home\Model\MemberModel();
    return $MemberObj->get_headpic($member_id);
}

 /**
 * 获取后台管理员名称
 * @param int member_id 供应商ID
 * @return type 返回供应商名称
 */
function show_admin_name($admin_id) {
    $AdminObj = new \Fwadmin\Model\AdminModel();
    return $AdminObj->show_admin_name($admin_id);
}


/*
 * 转换字符编码
 */
function iconvstr($str) {
    $encode = mb_detect_encoding($str, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
    if ($encode != "UTF-8") {  //所有不是UTF-8的全部当GB2312转换,不是很严谨
        $str = iconv($encode, "UTF-8", $str);
    }
    return $str;
}

/**
 * 检查是否是整形
 * @param int $str 字符串
 * @return bool true表示是 
 */
function check_int($str) {
    return preg_match('/^\d+$/',$str);
}

/**
 * 检查是否是浮点型
 * @param int $str 字符串
 * @return bool true表示是 
 */
function check_float($str) {
    return preg_match('/^\d+(\.\d+)?$/',$str);
}

function get_host(){
   if ($_SERVER['HTTPS'] != "on") {
       $host = 'http://'.$_SERVER['HTTP_HOST'];
   } else {
       $host = 'https://'.$_SERVER['HTTP_HOST'];
   }
   return $host;
}


/*
 * 截取字符串
 * $string 原字符串
 * $length 需要保留的字符长度
 * $rephtml 是否保留字符串中的 HTML 标签 0为不保留1为保留
 * $dot 截取后的连接符号
 * $pagechar 字符串编码
 * */
function str_cut($string, $length, $rephtml = 0, $dot = '...', $pagechar = 'utf8') {
    //保留转译后的HTML字符
    $rep_str1 = array('&nbsp;', '&amp;', '&quot;', '&lt;', '&gt;', '&#039;', '&ldquo;', '&rdquo;', '&middot;', '&mdash;');
    $rep_str2 = array(' ', '&', '"', '<', '>', "'", "“", "”", "·", "—");
    if ($rephtml == 0) {
        $string = htmlspecialchars_decode($string);
        $string = str_replace($rep_str1, $rep_str2, $string);
        $string = strip_tags($string);
    }
    $string = preg_replace("/\s/", " ", $string);
    $string = preg_replace("/^ +| +$/", '', $string);
    $string = preg_replace("/ {2,}/is", "  ", $string);
    $strlen = strlen($string);
    if ($strlen <= $length) {
        return $string;
    }
    $strcut = '';
    if ($pagechar == 'utf8') {
        $n = $tn = $noc = 0;
        while ($n < $strlen) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t < 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length) {
                break;
                $isdot = 1;
            }
        }
        if ($noc > $length) {
            $n -= $tn;
        }
        $strcut = substr($string, 0, $n);
        if ($n < $strlen) {
            $strcut = $strcut . $dot;
        }
    } else {
        for ($i = 0; $i < $length; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
        }
    }
    if ($rephtml == 0) {
        $string = str_replace($rep_str2, $rep_str1, $string);
    }
    return $strcut;
}



/**
 * 移动端判断 可在conf配置文件中用三元运算符定义默认模块http://detectmobilebrowsers.com/
 * @return bool
 */
function is_mobile() {
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($useragent, 0, 4))) {
        return true;
    } else {
        return false;
    }
}


/**
 * 富文本编辑器详情内容输出图片根目录替换(建议替换使用函数htmlspecialchars_decode)
 * @param $html 富文本编辑器保存的内容
 * @param bool $diff 是否区分大小写，默认替换区分大小写
 * @return string
 */
function htmldecode($html, $diff = true) {
    $WEB_LOCK_FILE = C('WEB_LOCK_FILE');
    $DETAIL_PIC_ROOT = include($WEB_LOCK_FILE);
    if (__ROOT__ == '' && $DETAIL_PIC_ROOT['DETAIL_PIC_ROOT'] != '' && C('DETAIL_PIC_RESET')) {
        return htmlspecialchars_decode($diff ? str_replace($DETAIL_PIC_ROOT['DETAIL_PIC_ROOT'], '', $html) : str_ireplace($DETAIL_PIC_ROOT['DETAIL_PIC_ROOT'], '', $html));
    } else {
        return htmlspecialchars_decode($html);
    }
}

function rand_username() {
    $tou =array('快乐','冷静','醉熏','潇洒','糊涂','积极','冷酷','深情','粗暴','温柔','可爱','愉快','义气','认真','威武','帅气','传统','潇洒','漂亮','自然','专一','听话','昏睡','狂野','等待','搞怪','幽默','魁梧','活泼','开心','高兴','超帅','留胡子','坦率','直率','轻松','痴情','完美','精明','无聊','有魅力','丰富','繁荣','饱满','炙热','暴躁','碧蓝','俊逸','英勇','健忘','故意','无心','土豪','朴实','兴奋','幸福','淡定','不安','阔达','孤独','独特','疯狂','时尚','落后','风趣','忧伤','大胆','爱笑','矮小','健康','合适','玩命','沉默','斯文','香蕉','苹果','鲤鱼','鳗鱼','任性','细心','粗心','大意','甜甜','酷酷','健壮','英俊','霸气','阳光','默默','大力','孝顺','忧虑','着急','紧张','善良','凶狠','害怕','重要','危机','欢喜','欣慰','满意','跳跃','诚心','称心','如意','怡然','娇气','无奈','无语','激动','愤怒','美好','感动','激情','激昂','震动','虚拟','超级','寒冷','精明','明理','犹豫','忧郁','寂寞','奋斗','勤奋','现代','过时','稳重','热情','含蓄','开放','无辜','多情','纯真','拉长','热心','从容','体贴','风中','曾经','追寻','儒雅','优雅','开朗','外向','内向','清爽','文艺','长情','平常','单身','伶俐','高大','懦弱','柔弱','爱笑','乐观','耍酷','酷炫','神勇','年轻','唠叨','瘦瘦','无情','包容','顺心','畅快','舒适','靓丽','负责','背后','简单','谦让','彩色','缥缈','欢呼','生动','复杂','慈祥','仁爱','魔幻','虚幻','淡然','受伤','雪白','高高','糟糕','顺利','闪闪','羞涩','缓慢','迅速','优秀','聪明','含糊','俏皮','淡淡','坚强','平淡','欣喜','能干','灵巧','友好','机智','机灵','正直','谨慎','俭朴','殷勤','虚心','辛勤','自觉','无私','无限','踏实','老实','现实','可靠','务实','拼搏','个性','粗犷','活力','成就','勤劳','单纯','落寞','朴素','悲凉','忧心','洁净','清秀','自由','小巧','单薄','贪玩','刻苦','干净','壮观','和谐','文静','调皮','害羞','安详','自信','端庄','坚定','美满','舒心','温暖','专注','勤恳','美丽','腼腆','优美','甜美','甜蜜','整齐','动人','典雅','尊敬','舒服','妩媚','秀丽','喜悦','甜美','彪壮','强健','大方','俊秀','聪慧','迷人','陶醉','悦耳','动听','明亮','结实','魁梧','标致','清脆','敏感','光亮','大气','老迟到','知性','冷傲','呆萌','野性','隐形','笑点低','微笑','笨笨','难过','沉静','火星上','失眠','安静','纯情','要减肥','迷路','烂漫','哭泣','贤惠','苗条','温婉','发嗲','会撒娇','贪玩','执着','眯眯眼','花痴','想人陪','眼睛大','高贵','傲娇','心灵美','爱撒娇','细腻','天真','怕黑','感性','飘逸','怕孤独','忐忑','高挑','傻傻','冷艳','爱听歌','还单身','怕孤单','懵懂');
    $do  = array("的","爱","","与","给","扯","和","用","方","打","就","迎","向","踢","笑","闻","有","等于","保卫","演变");
    $wei =array('嚓茶','凉面','便当','毛豆','花生','可乐','灯泡','哈密瓜','野狼','背包','眼神','缘分','雪碧','人生','牛排','蚂蚁','飞鸟','灰狼','斑马','汉堡','悟空','巨人','绿茶','自行车','保温杯','大碗','墨镜','魔镜','煎饼','月饼','月亮','星星','芝麻','啤酒','玫瑰','大叔','小伙','哈密瓜，数据线','太阳','树叶','芹菜','黄蜂','蜜粉','蜜蜂','信封','西装','外套','裙子','大象','猫咪','母鸡','路灯','蓝天','白云','星月','彩虹','微笑','摩托','板栗','高山','大地','大树','电灯胆','砖头','楼房','水池','鸡翅','蜻蜓','红牛','咖啡','机器猫','枕头','大船','诺言','钢笔','刺猬','天空','飞机','大炮','冬天','洋葱','春天','夏天','秋天','冬日','航空','毛衣','豌豆','黑米','玉米','眼睛','老鼠','白羊','帅哥','美女','季节','鲜花','服饰','裙子','白开水','秀发','大山','火车','汽车','歌曲','舞蹈','老师','导师','方盒','大米','麦片','水杯','水壶','手套','鞋子','自行车','鼠标','手机','电脑','书本','奇迹','身影','香烟','夕阳','台灯','宝贝','未来','皮带','钥匙','心锁','故事','花瓣','滑板','画笔','画板','学姐','店员','电源','饼干','宝马','过客','大白','时光','石头','钻石','河马','犀牛','西牛','绿草','抽屉','柜子','往事','寒风','路人','橘子','耳机','鸵鸟','朋友','苗条','铅笔','钢笔','硬币','热狗','大侠','御姐','萝莉','毛巾','期待','盼望','白昼','黑夜','大门','黑裤','钢铁侠','哑铃','板凳','枫叶','荷花','乌龟','仙人掌','衬衫','大神','草丛','早晨','心情','茉莉','流沙','蜗牛','战斗机','冥王星','猎豹','棒球','篮球','乐曲','电话','网络','世界','中心','鱼','鸡','狗','老虎','鸭子','雨','羽毛','翅膀','外套','火','丝袜','书包','钢笔','冷风','八宝粥','烤鸡','大雁','音响','招牌','胡萝卜','冰棍','帽子','菠萝','蛋挞','香水','泥猴桃','吐司','溪流','黄豆','樱桃','小鸽子','小蝴蝶','爆米花','花卷','小鸭子','小海豚','日记本','小熊猫','小懒猪','小懒虫','荔枝','镜子','曲奇','金针菇','小松鼠','小虾米','酒窝','紫菜','金鱼','柚子','果汁','百褶裙','项链','帆布鞋','火龙果','奇异果','煎蛋','唇彩','小土豆','高跟鞋','戒指','雪糕','睫毛','铃铛','手链','香氛','红酒','月光','酸奶','银耳汤','咖啡豆','小蜜蜂','小蚂蚁','蜡烛','棉花糖','向日葵','水蜜桃','小蝴蝶','小刺猬','小丸子','指甲油','康乃馨','糖豆','薯片','口红','超短裙','乌冬面','冰淇淋','棒棒糖','长颈鹿','豆芽','发箍','发卡','发夹','发带','铃铛','小馒头','小笼包','小甜瓜','冬瓜','香菇','小兔子','含羞草','短靴','睫毛膏','小蘑菇','跳跳糖','小白菜','草莓','柠檬','月饼','百合','纸鹤','小天鹅','云朵','芒果','面包','海燕','小猫咪','龙猫','唇膏','鞋垫','羊','黑猫','白猫','万宝路','金毛','山水','音响','尊云','西安');
    $tou_num=rand(0,331);
    $do_num=rand(0,19);
    $wei_num=rand(0,327);
    $type = rand(0,1);
    if($type==0){
        $username=$tou[$tou_num].$do[$do_num].$wei[$wei_num];
    }else{
        $username=$wei[$wei_num].$tou[$tou_num];
    }
    return $username;
}


function is_weixin(){
    if (strpos($_SERVER['HTTP_USER_AGENT'],
            'MicroMessenger') !== false ) {
        return true;
    }
    return false;
}

function createNoncestr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++)
    {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

?>